package com.vdongchina.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子更新基本类型类...查看文档好好使用
 *
 * 用于多线程对同一数据的操作导致数据的不一致问题
 *
 * 基本实现都是unsafe包来实现
 *
 */
public class AtomicBaseData {


    //默认1
    static AtomicInteger ai = new AtomicInteger(1);

    //原子引用类型
    static AtomicReference<User> atomicReference = new AtomicReference<>();


    public static void main(String[] args) {
        /**
         * getAndIncrement 使用了 compareAndSwapInt 进行 CAS 自旋操作
         */
        System.out.println(ai.getAndIncrement());
        System.out.println(ai.get());

        User user = new User("yyy",1);
        atomicReference.set(user);
        User updateUser = new User("shinichi",12);
        atomicReference.compareAndSet(user,updateUser);
        System.out.println(atomicReference.get().getName());
        System.out.println(atomicReference.get().getAge());



    }



    public static class User{

        public User(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        private String name;

        private Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }


}
